import os
import subprocess
import threading
import time

import pyautogui
import requests

import test2
import variable


class SoftWareUpdate(object):
    """
    软件安装
    """

    def __init__(self, admin_password=variable.ADMIN_PASSWORD, update_url=''):
        self.admin_password = admin_password
        self.software_default_path = r'c:\poi\download_software_update.exe'
        self.update_url = update_url

    # 获取本机管理员密码
    def get_windows_users(self):
        users = []
        cmd = 'net user'
        output = subprocess.check_output(cmd, shell=True).decode('utf-8', errors="ignore")
        lines = output.split(' ')
        for line in lines:
            if 'User accounts' in line or '---------' in line:
                continue
            if line.strip() != '':
                users.append(line.split()[0])
        if 'sysadmin' in users:
            admin_user = 'sysadmin'
        else:
            admin_user = 'PC000'
        return admin_user

    # 执行安装软件
    def execution_software(self, software_path):
        users = []
        cmd = 'net user'
        output = subprocess.check_output(cmd, shell=True).decode('utf-8', errors="ignore")
        lines = output.split(' ')
        for line in lines:
            if 'User accounts' in line or '---------' in line:
                continue
            if line.strip() != '':
                users.append(line.split()[0])
        if 'sysadmin' in users:
            admin_user = 'sysadmin'

        else:
            admin_user = 'PC000'
        print(software_path)
        os.system("start cmd /k runas /user:" + admin_user + " \"{}\"".format(software_path))
        time.sleep(1)
        # 模拟输入密码
        for char in self.admin_password:
            pyautogui.typewrite(char)
            time.sleep(0.1)  # 添加适当的延迟以模拟人类输入速度
        # 模拟按下回车键以提交密码
        pyautogui.press('enter')

    # 下载安装软件
    def download_software(self):
        try:
            response = requests.get(self.update_url, stream=True)
            if response.status_code == 404:
                pyautogui.alert(text='软件连接失效，无法下载', title='信息')
            else:
                # downloader = test2.FileDownloader(self.update_url, self.software_default_path)
                with open(self.software_default_path, 'wb') as f:
                    f.write(response.content)
        except ConnectionError as ce:
            print(ce)

    def software_install_thread(self):
        t = threading.Thread(target=self.download_software, daemon=True)
        t.start()

# root = tk.Tk()
#
# root.geometry("500x100")
# lb=tk.Label(root,text='下载进度')
# progress_bar = ttk.Progressbar(root, length=400)
# lb.pack()
# progress_bar.pack()
#
# root.mainloop()
